﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Drawing;
using IronOne.SalesOne.BusinessObjects;


namespace IronOne.SalesOne.SalesOneWeb.Messaging
{
    public partial class UpadateMessage : SOSecurityPage
    {

        Facade.StructureFacade structureFacade = new Facade.StructureFacade();
        Facade.MessageFacade messageFacade = new Facade.MessageFacade();

        //static string userName = "kamal";
        //static string userId = "fa0714ba-8c04-4a75-9b82-a87766179bc1";
        static string userName;
        static string userId;
        static int messageId;

        static List<Branch> lstBranches;
        static List<SalesOneUnit> lstUnits;
        static List<string> lstSocodes;

        protected void Page_Load(object sender, EventArgs e)
        {
            ValidateUserCredentials(Request.Url.LocalPath);

            if (!IsPostBack)
            {
                
                if (Page.Request.Params["a"] != null)
                {
                    int intMessageId = Convert.ToInt32(Page.Request.Params["a"].ToString());

                    Message message = messageFacade.GetMessage(intMessageId);
                    /*Get The current User*/
                    MembershipUser membershipUser = Membership.GetUser(HttpContext.Current.User.Identity.Name);
                    userName = membershipUser.UserName;
                    User user = structureFacade.GetUser(userName);
                    userId = user.UserId.ToString();


                    SetDataSourceToFrom(structureFacade.GetUserTypesForUser("UserTypeId ASC", userName));
                    IniateValues(message);
                }              
            }
            ddlFrom.Enabled = false;

            lblError.ForeColor = Color.Black;
            lblError.Text = "";

        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                if (ddlFrom.SelectedIndex > 0)
                {
                    bool isValid = false;

                    ManageMessages updateMessage = new ManageMessages();
                    updateMessage.MessageId = Convert.ToInt32(Page.Request.Params["a"].ToString());
                    updateMessage.UserId = structureFacade.GetUser(userName).UserId;
                    updateMessage.Body = txtMessage.Text;
                    updateMessage.GroupId = structureFacade.GetGroup(userName).GroupId;
                    updateMessage.FromUserTypeId = Convert.ToInt32(ddlFrom.SelectedValue);
                    updateMessage.Broadcasted = chkBroadcast.Checked;

                    if (ddlBranch.SelectedIndex > 0)
                    {
                        if (ddlBranch.SelectedIndex == 1)
                            updateMessage.Branches = lstBranches;
                        else
                        {
                            updateMessage.BranchId = Convert.ToInt32(ddlBranch.SelectedValue);
                            List<Branch> lst = new List<Branch>();
                            lst.Add(lstBranches.Find(GetBranch));
                            updateMessage.Branches = lst;
                        }

                        isValid = true;

                    }
                    if (ddlUnit.SelectedIndex > 0)
                    {
                        if (ddlUnit.SelectedIndex == 1)
                            updateMessage.Units = lstUnits;
                        else
                        {
                            List<SalesOneUnit> lst = new List<SalesOneUnit>();
                            lst.Add(lstUnits.Find(GetUnit));
                            updateMessage.Units = lst;
                        }

                        isValid = true;

                    }
                    if (ddlSOCode.SelectedIndex > 0)
                    {
                        if (ddlSOCode.SelectedIndex == 1)
                            updateMessage.SOCodes = lstSocodes;
                        else
                        {
                            List<string> lst = new List<string>();
                            lst.Add(lstSocodes.Find(GetSOCode));
                            updateMessage.SOCodes = lst;
                        }

                        isValid = true;
                    }
                    if (isValid)
                    {
                        messageFacade.UpdateMessage(updateMessage);
                        Response.Redirect("~/Messaging/SearchMessages.aspx");
                    }
                    else
                    {
                        lblError.ForeColor = Color.Red;
                        lblError.Text = "Please select a recipient.";
                    }
                }
                else
                {
                    lblError.ForeColor = Color.Red;
                    lblError.Text = "Please select a user type.";
                }
            }
            catch
            {
                lblError.ForeColor = Color.Red;
                lblError.Text = "Error in updating message. Please check the entered values again.";
            }
        }

        public void SetDataSourceToBranches(List<Branch> branches)
        {
            ddlBranch.DataSource = branches;
            ddlBranch.DataTextField = "BranchName";
            ddlBranch.DataValueField = "BranchID";
            ddlBranch.DataBind();

            InsertDDLItems(ddlBranch, "Select...", 0);
            InsertDDLItems(ddlBranch, "Select All", 1);
        }

        public void SetDataSourceToUnits(List<SalesOneUnit> units)
        {
            ddlUnit.DataSource = units;
            ddlUnit.DataTextField = "Name";
            ddlUnit.DataValueField = "UnitId";
            ddlUnit.DataBind();

            InsertDDLItems(ddlUnit, "Select...", 0);
            InsertDDLItems(ddlUnit, "Select All", 1);
        }

        public void SetDataSourceToSoCode(List<string> users)
        {
            ddlSOCode.DataSource = users;
            ddlSOCode.DataBind();

            InsertDDLItems(ddlSOCode, "Select...", 0);
            InsertDDLItems(ddlSOCode, "Select All", 1);
        }

        public void SetDataSourceToSoCode(List<User> users)
        {
            ddlSOCode.DataSource = users;
            ddlSOCode.DataTextField = "Name";
            ddlSOCode.DataValueField = "UserId";
            ddlSOCode.DataBind();

            InsertDDLItems(ddlSOCode, "Select...", 0);
            InsertDDLItems(ddlSOCode, "Select All", 1);
        }

        public void SetDataSourceToFrom(List<UserType> userTypes)
        {
            ddlFrom.DataSource = userTypes;
            ddlFrom.DataTextField = "UserTypeName";
            ddlFrom.DataValueField = "UserTypeId";
            ddlFrom.DataBind();

            InsertDDLItems(ddlFrom, "Select...", 0);
            //InsertDDLItems(ddlFrom, "Select All", 1);
        }

        public void InsertDDLItems(DropDownList ddl, string Text, int Position)
        {
            ListItem item = new ListItem(Text, Text);
            ddl.Items.Insert(Position, Text);
        }

        protected void chkBroadcast_CheckedChanged(object sender, EventArgs e)
        {
            DisableControlsForBroadcasting();
        }

        public void DisableControlsForBroadcasting()
        {
            if (chkBroadcast.Checked)
            {
                EnableControls(false);
            }
            else
            {
                EnableControls(true);
            }
        }

        protected void ddlUnit_SelectedIndexChanged(object sender, EventArgs e)
        {

            SetValuesForUnitValue();
        }

        protected void ddlFrom_SelectedIndexChanged(object sender, EventArgs e)
        {
            SetValuesForFromValue();
        }

        public void DisableControlsForHQ()
        {
            chkBroadcast.Enabled = false;
            chkBroadcast.Checked = false;
            DisableControlsForBroadcasting();
        }

        public void EnableControls(bool enabled)
        {
            ddlBranch.Enabled = enabled;
            ddlUnit.Enabled = enabled;
            ddlSOCode.Enabled = enabled;
        }

        private bool GetBranch(Branch branch)
        {
            if (branch.BranchId == Convert.ToInt32(ddlBranch.SelectedValue))
                return true;
            else
                return false;

        }

        private bool GetUnit(SalesOneUnit unit)
        {
            if (unit.UnitId == Convert.ToInt32(ddlUnit.SelectedValue))
                return true;
            else
                return false;
        }

        private bool GetSOCode(string soCode)
        {
            if (soCode.Equals(ddlSOCode.SelectedItem.Text))
                return true;
            else
                return false;

        }

        protected void ddlBranch_SelectedIndexChanged(object sender, EventArgs e)
        {
            SetValuesForBranchValue();
        }

        private void IniateValues(Message message)
        {
            txtMessage.Text = message.MessageBody;

            //ddlFrom.SelectedValue = message.MessageFromUserTypeID.ToString();
            ddlFrom.SelectedValue = (structureFacade.GetUserTypeForUser(userName).UserTypeId.ToString());
            SetValuesForFromValue();

            chkBroadcast.Checked = (message.UserTypeId==1);

            if (chkBroadcast.Checked)
                DisableControlsForBroadcasting();

            if (message.UserTypeId == 2)
            {
                ddlBranch.SelectedIndex = 1;
                SetValuesForBranchValue();
            }
            else if (message.UserTypeId == 3)
            {
                ddlBranch.SelectedValue = message.NodeId.ToString();
                SetValuesForBranchValue();
            }
               
            else if (message.UserTypeId == 4)
            {
                ddlUnit.SelectedValue = message.NodeId.ToString();
                SetValuesForUnitValue();
            }
            else
            {
                ddlSOCode.SelectedValue = message.SoCodeId;
            }

        }

        private void SetValuesForFromValue()
        {
            if (ddlFrom.SelectedItem.Text.Equals("HQ", StringComparison.InvariantCultureIgnoreCase))
            {
                chkBroadcast.Enabled = true;
                lstBranches = structureFacade.GetBranches("BranchName ASC");
                SetDataSourceToBranches(lstBranches);
                ddlUnit.Items.Clear();
                ddlSOCode.Items.Clear();
                EnableControls(true);
            }
            /*If Group selected populate the branches according to the group*/
            else if (ddlFrom.SelectedItem.Text.Equals("Group", StringComparison.InvariantCultureIgnoreCase))
            {
                DisableControlsForHQ();
                lstBranches = structureFacade.GetBranchesForGroup("BranchName ASC", userName);
                SetDataSourceToBranches(lstBranches);
                //populate branches
                ddlUnit.Items.Clear();
                ddlSOCode.Items.Clear();
                EnableControls(true);
            }
            /*If brnch - populate the branches according to the selected branch */
            else if (ddlFrom.SelectedItem.Text.Equals("Branch", StringComparison.InvariantCultureIgnoreCase))
            {
                DisableControlsForHQ();
                //populate units
                lstUnits = structureFacade.GetUnitsInBranch("UnitName", userName);
                SetDataSourceToUnits(lstUnits);
                ddlSOCode.Items.Clear();
                ddlBranch.Enabled = false;
            }
            /*If units then -units acoording to the .....*/
            else if (ddlFrom.SelectedItem.Text.Equals("Unit", StringComparison.InvariantCultureIgnoreCase))
            {
                lstSocodes = structureFacade.GetSOsForUser("", userName);
                SetDataSourceToSoCode(lstSocodes);
                DisableControlsForHQ();
                //populate socodes
                ddlBranch.Enabled = false;
                ddlBranch.Items.Clear();
            }


        }

        private void SetValuesForBranchValue()
        {
            EnableControls(true);
            if (ddlBranch.SelectedIndex > 1)
            {
                lstUnits = structureFacade.GetUnitsInBranch(int.Parse(ddlBranch.SelectedValue));
                SetDataSourceToUnits(lstUnits);

                ddlUnit.Items.Clear();
                ddlSOCode.Items.Clear();
            }
            else if (ddlBranch.SelectedIndex == 1)
            {
                ddlUnit.Enabled = false;
                ddlUnit.Items.Clear();
                ddlSOCode.Enabled = false;
                ddlSOCode.Items.Clear();
            }
        }

        private void SetValuesForUnitValue()
        {
            EnableControls(true);
            if (ddlUnit.SelectedIndex > 1)
            {
                lstSocodes = structureFacade.GetSOsInUnit(int.Parse(ddlUnit.SelectedValue));
                SetDataSourceToSoCode(lstSocodes);

                ddlSOCode.Items.Clear();
            }
            else if (ddlUnit.SelectedIndex == 1)
            {
                ddlSOCode.Enabled = false;
                ddlSOCode.Items.Clear();
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Messaging/SearchMessages.aspx");
        }
    }
}
